package com.mycompany.app.hr.hrinterface.importing.csvjdbc.spring;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;

/**
 * 
 * @author Shawn.guo
 *
 */
public class CsvJdbcConnectionFactoryBean implements FactoryBean,
        InitializingBean {
    private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory
            .getLog(CsvJdbcConnectionFactoryBean.class);

    private String csvDir;

    private String csvDriverUrl;

    public String getCsvDir() {

        return csvDir;
    }

    public void setCsvDir(String csvDir) {

        Assert.isTrue(new File(csvDir).isDirectory());
        this.csvDir = csvDir;
        this.csvDriverUrl = "jdbc:relique:csv:" + csvDir;
    }

    public Object getObject() throws Exception {

        Connection conn = DriverManager.getConnection(csvDriverUrl);
        if (log.isDebugEnabled())
            log.debug("Get CsvJdbc Connection " + conn);

        return conn;
    }

    @SuppressWarnings("unchecked")
    public Class getObjectType() {

        return Connection.class;
    }

    public boolean isSingleton() {

        return false;
    }

    public void afterPropertiesSet() throws Exception {

        // load the driver into memory
        try {
            Class.forName("org.relique.jdbc.csv.CsvDriver");
        } catch (ClassNotFoundException e) {
            log.error("Fail to load the drive of CSV file into the memory.", e);
        }

        log.info("Load the drive of Csv, Excel into the memory.");
    }

}
